﻿#include "maindialog.h"
#include "ui_maindialog.h"
#include <QStackedLayout>
#include <QWidget>
#include "cruntimesetting.h"
#include <QMenu>
#include <QCloseEvent>
#include <QDebug>
#include "ctimespanintvalidator.h"
#include <QDir>
#include <QTextEdit>

void MainDialog::Data2UI()
{
    ui->cbxShowSecond->setChecked(ss::CRuntimeSetting::GetConfig().bShowSecond);
    ui->cbxShowDate->setChecked(ss::CRuntimeSetting::GetConfig().bShowDate);
    ui->cbxRunOnStartup->setChecked(ss::CRuntimeSetting::GetConfig().bRunOnStartup);
    ui->editTimeSpan->setText(QString::number(ss::CRuntimeSetting::GetConfig().nLockSpan / 1000));
    ui->editTextConfig->setText(ss::CRuntimeSetting::GetConfig().sentence);
}

void MainDialog::InitSystemTray()
{
    m_tray = new QSystemTrayIcon(this);
    m_tray->setIcon(QIcon(":/res/images/clock.png"));
    m_tray->setToolTip("桌面时钟屏保");
    QMenu* menu = new QMenu();
    QAction* pActExit = new QAction(QIcon(":/res/images/exit.png"), "退出(&X)");
    QAction* pActSettings = new QAction(QIcon(":/res/images/setting2.png"), "设置(&S)");
    menu->addAction(pActSettings);
    menu->addAction(pActExit);
    m_tray->setContextMenu(menu);
    connect(pActExit, SIGNAL(triggered(bool)), this, SLOT(triggerSystemTrayExit(bool)));
    connect(pActSettings, SIGNAL(triggered(bool)), this, SLOT(triggerSystemTraySetting(bool)));
    connect(m_tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onActivated(QSystemTrayIcon::ActivationReason)));
    m_tray->show();
}

MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);
    this->setFixedSize(this->width(), this->height());
    setWindowTitle("时钟屏保");
    setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint));
    m_pScreenProtector = new CScreenProtectorMag(this);
    m_bShowTrayMsgOnce = true;

    QHBoxLayout* layout = new QHBoxLayout();

    m_pStackListWidget = new QListWidget();
    m_pStackListWidget->setMinimumWidth(50);
    m_pStackListWidget->addItem("设置");
    m_pStackListWidget->addItem("关于");
    m_pStackListWidget->addItem("赞助");
    m_pStackListWidget->setCurrentRow(0);

    QStackedLayout* stackLayout = new QStackedLayout();
    QWidget* setting = new QWidget;
    QGridLayout* settingGridLayout = new QGridLayout;
    settingGridLayout->addWidget(ui->lblShowSecond, 0, 0, 1, 1);
    settingGridLayout->addWidget(ui->cbxShowSecond, 0, 1, 1, 1);
    settingGridLayout->addWidget(ui->lblShowDate, 1, 0, 1, 1);
    settingGridLayout->addWidget(ui->cbxShowDate, 1, 1, 1, 2);
    settingGridLayout->addWidget(ui->lblRunOnStartup, 2, 0, 1, 1);
    settingGridLayout->addWidget(ui->cbxRunOnStartup, 2, 1, 1, 1);    
    settingGridLayout->addWidget(ui->lblTextConfig,3, 0, 1, 1);
    settingGridLayout->addWidget(ui->editTextConfig, 3, 1, 1, 2);
    settingGridLayout->addWidget(ui->lblTimeSpan, 4, 0, 1, 1);
    settingGridLayout->addWidget(ui->editTimeSpan, 4, 1, 1, 1);
    settingGridLayout->addWidget(ui->btnPreview, 4, 2, 1, 2);
    settingGridLayout->addWidget(ui->btnOK, 5, 0, 1, 1);
    settingGridLayout->addWidget(ui->btnApply, 5, 1, 1, 1);
    settingGridLayout->addWidget(ui->btnCancel, 5, 2, 1, 1);

    ui->btnOK->setFixedSize(110, 40);
    ui->btnCancel->setFixedSize(110, 40);
    ui->btnApply->setFixedSize(110, 40);
    ui->btnPreview->setFixedSize(110, 40);
    ui->editTimeSpan->setValidator(new ss::CTimeSpanIntValidator(MIN_LOCK_SPAN, MAX_LOCK_SPAN, this));
    ui->editTimeSpan->setPlaceholderText("3秒到30天");
    ui->editTimeSpan->setToolTip("范围从3秒到30天，即[3, 2592000]");
    ui->editTextConfig->setMaxLength(MAX_CONFIG_SENTENCE_LENGTH);
    ui->editTextConfig->setPlaceholderText(QString("最多输入%1个字符").arg(MAX_CONFIG_SENTENCE_LENGTH));

    setting->setLayout(settingGridLayout);

    QFile aboutFile(QDir::cleanPath(QApplication::applicationDirPath().append("\\postinstall.txt")));
    qDebug() << QDir::cleanPath(QApplication::applicationDirPath().append("\\postinstall.txt"));
    QString strAbout("微信：263873808，加好友注明来自ScreenProtecter\r\n可以反馈bug或提出建议，有软件开发需求也可以联络， Thanks！");
    bool bOK = aboutFile.open(QIODevice::ReadOnly | QIODevice::Text);
    if (bOK)
    {
        QByteArray ret = aboutFile.readAll();
        if (ret.length() > 0)
        {
             strAbout = QString(ret);
         }
        aboutFile.close();
    }
    qDebug() << __FUNCTION__ << "about:" << strAbout;

    QWidget* about = new QWidget;
    QVBoxLayout* vBoxLayoutForAboutText = new QVBoxLayout();
    QTextEdit* editAbout = new QTextEdit(about);
    editAbout->setText(strAbout);
    editAbout->setReadOnly(true);
    editAbout->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    vBoxLayoutForAboutText->addWidget(editAbout);
    about->setLayout(vBoxLayoutForAboutText);

    QWidget* donate = new QWidget;
    QVBoxLayout* vBoxLayout = new QVBoxLayout();
    QFrame* frame = new QFrame();
    //frame->setStyleSheet("background-image:url(':/res/images/wechatpay.png');background-position:center;background-size:contain;background-repeat:no-repeat");
    //frame->setStyleSheet("border-image:url(':/res/images/wechatpay.png');background-position:center;background-size:contain;background-repeat:no-repeat");
    frame->setStyleSheet("border-image:url(':/res/images/wechatpay.png')");


    vBoxLayout->addWidget(frame, 15);
    donate->setLayout(vBoxLayout);

    stackLayout->addWidget(setting);
    stackLayout->addWidget(about);
    stackLayout->addWidget(donate);
    stackLayout->setCurrentIndex(0);

    layout->addWidget(m_pStackListWidget, 1);
    layout->addLayout(stackLayout, 3);

    setLayout(layout);
    connect(m_pStackListWidget, SIGNAL(currentRowChanged(int)), stackLayout, SLOT(setCurrentIndex(int)));
    Data2UI();
    InitSystemTray();
}

MainDialog::~MainDialog()
{
    qDebug() << __FUNCTION__;
    delete ui;
}




void MainDialog::on_btnOK_clicked()
{
    qDebug() << __FUNCTION__;
    ChangeConfig();
    if (m_tray && m_tray->isVisible())
    {
        hide();
        if (m_bShowTrayMsgOnce)
        {
            m_bShowTrayMsgOnce = false;
            m_tray->showMessage("ScreenProtecter","屏幕保护程序运行在后台");
        }
    }
    else
    {
        accept();
    }
}

void MainDialog::on_btnCancel_clicked()
{
    qDebug() << __FUNCTION__;
    if (m_tray && m_tray->isVisible())
    {
        hide();
        if (m_bShowTrayMsgOnce)
        {
            m_bShowTrayMsgOnce = false;
            m_tray->showMessage("ScreenProtecter","屏幕保护程序运行在后台");
        }
    }
    else
    {
        reject();
    }
}

void MainDialog::on_btnApply_clicked()
{
    qDebug() << __FUNCTION__;
    ChangeConfig();
}

void MainDialog::triggerSystemTrayExit(bool checked)
{
    Q_UNUSED(checked)
    qDebug() << __FUNCTION__;
    if (m_tray)
    {
        delete m_tray;
    }
    QApplication::exit(0);
}

void MainDialog::triggerSystemTraySetting(bool checked)
{
    Q_UNUSED(checked);
    Data2UI();
    show();
    if (m_pStackListWidget)
    {
        m_pStackListWidget->setCurrentRow(0);
        // 使窗口变为激活窗口（标题栏从灰色变为正常）
        activateWindow();
    }
}

void MainDialog::onActivated(QSystemTrayIcon::ActivationReason action)
{
    switch (action) {
    case QSystemTrayIcon::DoubleClick:
        Data2UI();
        show();
        activateWindow();
        break;
    default:
        break;
    }
}

void MainDialog::ChangeConfig()
{
    bool bShowDate = ui->cbxShowDate->isChecked();
    bool bShowSecond = ui->cbxShowSecond->isChecked();
    bool bRunOnStartup = ui->cbxRunOnStartup->isChecked();
    int nSeconds = ui->editTimeSpan->text().toInt();
    QString sentence = ui->editTextConfig->text();
    ss::CRuntimeSetting::SetConfig(bShowSecond, bShowDate, nSeconds, bRunOnStartup, sentence);
}

void MainDialog::closeEvent(QCloseEvent *e)
{
    qDebug() << __FUNCTION__;
    if (m_tray && m_tray->isVisible())
    {
        hide();
        e->ignore();
        if (m_bShowTrayMsgOnce)
        {
            m_bShowTrayMsgOnce = false;
            m_tray->showMessage("ScreenProtecter","屏幕保护程序运行在后台");
        }
    }
    else
    {
        e->accept();
    }

}

void MainDialog::on_btnPreview_clicked()
{
    qDebug() << __FUNCTION__;
    if (m_pScreenProtector)
    {
        bool bShowDate = ui->cbxShowDate->isChecked();
        bool bShowSecond = ui->cbxShowSecond->isChecked();
        bool bRunOnStartup = ui->cbxRunOnStartup->isChecked();
        int nSeconds = ui->editTimeSpan->text().toInt();
        QString sentence = ui->editTextConfig->text();
        ss::CRuntimeSetting::SetPreviewConfig(bShowSecond, bShowDate, sentence);
        m_pScreenProtector->Preview(bShowSecond, bShowDate, nSeconds, bRunOnStartup, sentence);
    }
}
